package com.mopencode.seckill.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lxs.legou.common.utils.DateUtil;
import com.lxs.legou.common.utils.SystemConstants;
import com.mopencode.seckill.dao.SeckillGoodsDao;
import com.mopencode.seckill.po.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Mcb
 * @date 2022/4/6
 * @apiNote 定时任务类，每个x秒把秒杀商品加载入redis中
 */
@Component
public class SeckillGoodsPushTask {
    public static void main(String[] args) {
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            System.out.println(dateMenu);
        }
    }
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsDao seckillGoodsDao;

    @Scheduled(cron = "0 */10 * * * ?")
    //@Scheduled(cron = "0/30 * * * * ?")
    public void loadGoodsPushRedis(){
        System.out.println("定时任务执行");
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            //2020122110
            String extName = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYYMMDDHH);
            QueryWrapper<SeckillGoods> query = Wrappers.<SeckillGoods>query();
            query.gt("stock_count_", 0);
            query.eq("status_", 1);
            query.eq("date_menu_", extName);
            //现有的redis中的秒杀商品id
            Set keys = redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX + extName).keys();
            if (keys != null && keys.size() >0) {
                query.notIn("id_", keys);
            }
            List<SeckillGoods> seckillGoods = seckillGoodsDao.selectList(query);
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(SystemConstants.SEC_KILL_GOODS_PREFIX+extName).put(seckillGood.getId(),seckillGood);
                //设置过期时间
                redisTemplate.expire(SystemConstants.SEC_KILL_GOODS_PREFIX+extName,2, TimeUnit.HOURS);
            }
        }
    }
}
